'use strict';

module.exports = () => {
  // console.log(options);
  return async function jwtErr(ctx, next) {
    const whiteList = [ '/', '/api/verify', '/api/users/login', '/api/users/register' ];
    if (whiteList.indexOf(ctx.request.url) !== -1) { // 配置白名单
      await next();
      return;
    }
    const token = ctx.request.header.authorization;
    let decode = '';
    if (token) {
      try {
        // 解码token
        decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        ctx.state = decode;
        await next();
        // console.log('decode======>', decode);
      } catch (error) {
        ctx.helper.res_fail(error, 'token失效', 401);
        return;
      }
    } else {
      ctx.helper.res_fail(false, '无效token', 401);
    }
  };
};
